package com.me.safebox.ui.photo;

import java.util.ArrayList;
import java.util.List;

import net.tsz.afinal.FinalBitmap;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;

import com.me.safebox.R;
import com.me.safebox.service.FileScanner;
import com.me.safebox.service.FileScanner.FilePackage;
import com.me.safebox.service.FileScanner.ScannerListener;
import com.me.safebox.ui.MainApp;
import com.me.safebox.ui.adapter.MediaScanAdapter;
import com.me.safebox.utils.Dev_MountInfo;
import com.me.safebox.utils.Dev_MountInfo.DevInfo;

/**
 * 
 * @ClassName: AlbumScanner
 * @Description:相册扫描
 * @author: Matrix
 * @date: 2012-12-10 下午4:44:57
 * 
 */
public class MediaScan extends Activity implements ScannerListener, OnClickListener {
	private GridView mGridView = null;

	private FileScanner mFileScanner = null;

	private Button scanBtn = null;

	private Button filterBtn = null;

	private TextView filtTextView = null;

	private boolean isProccess = false;

	//private ProgressDialog mProgressDlg = null;
	
	private TextView titleView = null;
	
	private TextView backText = null;

	private TextView internTextView = null;

	private TextView externalTextView = null;

	private static final int SCANNING_NEW_PACKAGE = 1;

	private static final int SCANNING_FINISHED = 2;

	private MediaScanAdapter mPackageAdapter = null;

	private List<String> fileExtension = new ArrayList<String>();

	private AlertDialog mDialog = null;

	private static final String[] EXTENSION_ARRAY = new String[] { "png", "jpg", "amr", "mp3" };

	private boolean[] init = new boolean[] { false, false, false, false };

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.layout_mediascan);
		mGridView = (GridView) findViewById(R.id.ablum_gridview);
		titleView = (TextView) findViewById(R.id.scan_title);
		backText = (TextView) findViewById(R.id.back_tv);
		backText.setOnClickListener(this);
//		scanBtn = (Button) findViewById(R.id.scanBtn);
//		filterBtn = (Button) findViewById(R.id.filtBtn);
//		filtTextView = (TextView) findViewById(R.id.filt_view);
//		filterBtn.setOnClickListener(this);
//		scanBtn.setOnClickListener(this);
		mFileScanner = new FileScanner(this);
		
		
//		mProgressDlg = new ProgressDialog(this);
//		mProgressDlg.setTitle("正在扫描sd卡");
//		mProgressDlg.setCancelable(false);
//		mProgressDlg.setCanceledOnTouchOutside(false);
		
		
//		internTextView = (TextView) findViewById(R.id.internal_sdinfo_view);
//		externalTextView = (TextView) findViewById(R.id.external_sdinfo_view);
		mPackageAdapter = new MediaScanAdapter(this, MainApp.getFinalBitmap());
		mGridView.setAdapter(mPackageAdapter);

		//checkMounted();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onResume()
	 */
	@Override
	protected void onResume() {
		super.onResume();
		List<String> fileExtension = new ArrayList<String>();
		fileExtension.add(EXTENSION_ARRAY[1]);
		startScanningProcess(fileExtension);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onPause()
	 */
	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		if (this.mPackageAdapter != null) {
			mPackageAdapter.clearData();
			mPackageAdapter.clearView();
		}
		MainApp.getFinalBitmap().clearMemeoryCache();
	}

	private void checkMounted() {
		Dev_MountInfo dev = Dev_MountInfo.getInstance();
		DevInfo internal_info = dev.getInternalInfo();
		if (internal_info != null) {
			String path = internal_info.getPath();
			internTextView.setText("内置sd卡:" + path);
		} else {
			internTextView.setText("无内置sd卡");
		}
		DevInfo external_info = dev.getExternalInfo();
		if (external_info != null) {
			String path = external_info.getPath();
			externalTextView.setText("外置sd卡:" + path);
		} else {
			externalTextView.setText("无外置sd卡");
		}
	}

	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case SCANNING_NEW_PACKAGE:
				FilePackage filePkg = (FilePackage) msg.obj;
				mPackageAdapter.setData(filePkg);
				mPackageAdapter.notifyDataSetChanged();
				break;
			case SCANNING_FINISHED:
//				if (mProgressDlg != null && mProgressDlg.isShowing()) {
//					mProgressDlg.dismiss();
//				}
				int[] result = (int[]) msg.obj;
				titleView.setText("本次扫描到:" + result[1] + "个文件,耗时:" + msg.arg1 + "秒");
				//Toast.makeText(MediaScan.this, "您本次扫描耗时:" + msg.arg1 + "秒 , 共扫描文件:" + result[0] + "个, 命中" + result[1] + "个," + "共扫描包:" + result[2] + "个",

				//Toast.LENGTH_LONG).show();
				break;
			}
		}
	};

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.me.safephoto.FileScanner.ScannerListener#onSannerStart()
	 */
	long startTimeStamp = 0;
	long endTimeStamp = 0;

	@Override
	public void onSannerStart() {
		startTimeStamp = System.currentTimeMillis();

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.me.safephoto.FileScanner.ScannerListener#onScannerNewPkg()
	 */
	@Override
	public void onScannerNewPkg(FilePackage filePkg) {
		Message msg = mHandler.obtainMessage();
		msg.obj = filePkg;
		msg.what = SCANNING_NEW_PACKAGE;
		mHandler.sendMessage(msg);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.me.safephoto.FileScanner.ScannerListener#onScannerFinish()
	 */
	@Override
	public void onScannerFinish(int fileTotal, int hitFileTotal, int folderTotal) {
		isProccess = false;
		endTimeStamp = System.currentTimeMillis();
		long wastTime = (endTimeStamp - startTimeStamp) / 1000;
		startTimeStamp = 0;
		endTimeStamp = 0;
		Message msg = mHandler.obtainMessage();
		int[] resultInfo = { fileTotal, hitFileTotal, folderTotal };
		msg.obj = resultInfo;
		msg.arg1 = (int) wastTime;
		msg.what = SCANNING_FINISHED;
		mHandler.sendMessage(msg);
	}

	/**
	 * 开始扫描SD
	 * 
	 * @param fileExtension
	 */
	private void startScanningProcess(List<String> fileExtension) {
		if (isProccess == true) {
			Toast.makeText(this, "正在扫描中...", Toast.LENGTH_SHORT).show();
			return;
		}
		// mPackageAdapter.clearData();
		if (fileExtension == null || fileExtension.size() == 0) {
			Toast.makeText(this, "请先选择您要扫描的文件类型", Toast.LENGTH_SHORT).show();
			return;
		}
		//if (mProgressDlg != null && !mProgressDlg.isShowing()) {
			//清一下屏幕
			mPackageAdapter.clearData();
			mPackageAdapter.clearView();
			mPackageAdapter.notifyDataSetChanged();
			//mProgressDlg.show();
		//}
		mFileScanner.startScanning(Environment.getExternalStorageDirectory(), fileExtension);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.view.View.OnClickListener#onClick(android.view.View)
	 */
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.back_tv:
			Intent intent = new Intent();
			intent.setClass(this, SafeAlbum.class);
			startActivity(intent);
			finish();
//		case R.id.scanBtn:
//			startScanningProcess(fileExtension);
//			break;
//		case R.id.filtBtn:
//			this.mDialog = new AlertDialog.Builder(this).setTitle("多项选择").setIcon(android.R.drawable.ic_dialog_alert)
//					.setMultiChoiceItems(EXTENSION_ARRAY, init, new DialogInterface.OnMultiChoiceClickListener() {
//						@Override
//						public void onClick(DialogInterface dialog, int which, boolean isChecked) {
//
//						}
//					}).setPositiveButton("确定", new DialogInterface.OnClickListener() {
//
//						@Override
//						public void onClick(DialogInterface dialog, int which) {
//							String temp = " | ";
//							for (int i = 0; i < init.length; i++) {
//								if (init[i]) {
//									temp = temp + EXTENSION_ARRAY[i] + " | ";
//									fileExtension.add(EXTENSION_ARRAY[i]);
//								}
//							}
//							filtTextView.setText("过滤文件类型:" + temp);
//						}
//					}).setNegativeButton("取消", new DialogInterface.OnClickListener() {
//
//						@Override
//						public void onClick(DialogInterface dialog, int which) {
//							System.out.println("NegativeButton= " + which);
//							dialog.dismiss();
//						}
//					}).create();
//			this.mDialog.show();
//
		}
//
	}

}